package net.omnivention.wulumuqi;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class WuluFormActionServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private final static Logger logger = Logger.getLogger(WuluFormActionServlet.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			ServletContext servletContext = getServletContext();

			String htmlFile = request.getParameter("htmlFile");
			request.setAttribute("htmlFile", htmlFile);
			logger.debug("htmlFile=" + htmlFile);
			if (htmlFile == null) {
				String referer = request.getHeader("Referer");
				logger.debug("referer=" + referer);
				Pattern p = Pattern.compile(".*/(\\w*\\.(html|jsp))");
				Matcher m = p.matcher(referer);
				if (m.find()) {
					if (referer.indexOf(".html") > -1) {
						htmlFile = "file:///" + servletContext.getRealPath(m.group(1));
					} else {
						htmlFile = m.group(0);
					}
					request.setAttribute("htmlFile", htmlFile);
				}
			}
			logger.debug("htmlFile=" + htmlFile);
			HtmlDocument doc = WuluUtil.parseDocument(htmlFile);
			doc.init();
			doc.setRequest(request);
			doc.setResponse(response);
			doc.setServletContext(servletContext);

			boolean validForm = doc.validateForm();
			if (validForm) {
				executeAction(request, response, servletContext);
			} else {
				doc.applyManipulatorsInMetaTag();
				Format format = WuluUtil.getFormatter();
				XMLOutputter xmlPrettyPrinter = new XMLOutputter(format);
				xmlPrettyPrinter.output(doc, response.getOutputStream());
			}
		} catch (JDOMException e1) {
			logger.error(e1, e1);
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private void executeAction(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
			throws IOException {
		try {
			BSFManager manager = new BSFManager();
			manager.loadScriptingEngine("jython");
			manager.declareBean("request", request, HttpServletRequest.class);
			manager.declareBean("response", response, HttpServletResponse.class);
			manager.declareBean("out", response.getOutputStream(), ServletOutputStream.class);
			manager.declareBean("servletContext", servletContext, ServletContext.class);

			String scriptURL = request.getParameter("scriptURL");
			if (scriptURL.indexOf("http://") == -1) {
				scriptURL = "file:///" + servletContext.getRealPath(scriptURL);
			}
			String script = WuluUtil.getResource(scriptURL);
			manager.exec("jython", scriptURL, 0, 0, script);
		} catch (BSFException e) {
			logger.error(e, e);
		}
	}

}